<script setup>
	import {
		ref,
		reactive,
		nextTick,
		computed,
		onMounted
	} from 'vue'
	import {
		ElTable,
		ElTableColumn,
		ElPagination,
		ElInput,
		ElButton,ElMessageBox
	} from 'element-plus'
	import Drawer from '@/components/Drawer.vue'
	import ConsumableList from '@/components/ConsumableList.vue'
	import {
		getWareHouse,
		getDisposalList,
		addDisposal,
		getDisposalMaterialDetail,
		deleteConsumablesDisposal
	} from "@/api/ConsumablesDisposal.js"

	import {
		Search,
		Plus,
		Refresh,
		Delete,
		View
	} from '@element-plus/icons-vue'
	// 耗材处置搜索框绑定的位置id和处置单号
	const queryForm = ref({
		warehouseId: null,
		orderNo: ""
	})

	// 耗材处置中仓库的树形数据
	const wareHouse = ref([])

	// 获取仓库数据
	const getWareHouseData = () => {
		getWareHouse().then(res => {
			if (res.code === 200) {
				wareHouse.value = res.data
			}
		})
	}

	// 耗材处置列表数据
	const disposalList = ref([])

	// 获取处置列表
	const getDisposalListData = () => {
		getDisposalList().then(res => {
			if (res.code === 200) {
				disposalList.value = res.data
			}
		})
	}

	// 根据条件查询处置列表
	const handleDisposalSearch = () => {
		const params = {
			warehouseId: queryForm.value.warehouseId,
			orderNo: queryForm.value.orderNo
		}
		getDisposalList(params).then(res => {
			if (res.code === 200) {
				disposalList.value = res.data
			}
		})
	}

	const handleDisposalReset = () => {
		queryForm.value.warehouseId = null
		queryForm.value.orderNo = ""
		getDisposalListData()
	}

	// 新增耗材处置弹框状态
	const formVisible = ref(false)

	// 耗材处置弹框标题
	const title = ref('')

	//点击借出按钮
	const addDisposalData = () => {
		//重置表单 修改编辑状态
		resetForm()
		//弹框显示
		formVisible.value = true
		//弹框标题
		title.value = '新增耗材处置'
	}

	// 是否为编辑状态
	const isEditMode = ref(false)

	// 耗材处置表单实例对象
	const formRef = ref(null)

	// 耗材借用表单数据
	const disposalForm = ref({
		id: null,
		orderNo: "",
		warehouseId: null,
		warehouseName: "",
		type: null,
		status: null,
		operatorId: null,
		operator: "",
		createTime: null,
		remark: "",
		materialDisposalDetails: []
	})

	// 重置表单
	const resetForm = () => {
		isEditMode.value = false;
		formRef.value?.resetFields();
		disposalForm.value = {
			id: null,
			orderNo: "",
			warehouseId: null,
			warehouseName: "",
			type: null,
			status: null,
			operatorId: null,
			operator: "",
			createTime: null,
			remark: "",
			materialDisposalDetails: []
		}
	}

	// 定义子组件 ref
	// const consumablesListRef = ref(null)

	// 点击取消关闭弹框
	const handleCancel = () => {
		formVisible.value = false
		// 调用子组件的取消选中方法
		// consumablesListRef.value?.clearSelection()
	}

	const rules = {
		warehouseId: [{
			required: true,
			message: '请选择处置仓库',
			trigger: 'change'
		}],
		type: [{
			required: true,
			message: '请选择处置类型',
			trigger: 'change'
		}],
		remark: [{
			max: 200,
			message: '备注长度不能超过200个字符',
			trigger: 'blur'
		}]
	}

	// 提交耗材处置表单
	const handleSubmit = () => {
		// 添加表单校验
		if (disposalForm.value.materialDisposalDetails.length <= 0) return ElMessage.error('请选择耗材')
		formRef.value.validate(async (valid) => {
			if (valid) {
				addDisposal(disposalForm.value).then(res => {
					if (res.code === 200) {
						ElMessage.success(`处置成功`);
						formVisible.value = false;
						// 调用子组件的取消选中方法
						// consumablesListRef.value?.clearSelection()
						resetForm()
						getDisposalListData()
					}
				});
			}
		})
	}

	// 获取子组件选择耗材的资产
	const handleConsumablesSelect = (consumables) => {
		//console.log(consumables, 9999)

		if (consumables != null) {
			// 映射耗材数据到处置明细
			disposalForm.value.materialDisposalDetails = consumables.map(item => ({
				materialId: item.materialId,
				code: item.code,
				name: item.name,
				specification: item.specification,
				unit: item.unit,
				categoryId: item.categoryId,
				categoryName: item.categoryName,
				stock: item.quantity, // 将原库存数量映射到stock
				quantity: item.materialNum // 将用户输入的数量映射到quantity
			}))
		}
		//return disposalForm.value.materialDisposalDetails
	}

	// 控制 Drawer 显示状态
	const drawerVisible = ref(false)

	const showFormData = ref({
		id: "",
		orderNo: "",
		warehouseId: null,
		warehouseName: "",
		type: null,
		status: null,
		operatorId: null,
		operator: "",
		createTime: null,
		remark: "",
		materialDisposalDetails: []
	})

  const formDataValues = computed(() => [
    {
      label: '处置单号:',
      value: showFormData.value.orderNo
    },
    {
      label: '处置人:',
      value: showFormData.value.operator
    },
    {
      label: '单据状态:',
      value: showFormData.value.status
    },
    {
      label: '处置类型:',
      value: showFormData.value.type
    },
    {
      label: '处置仓库:',
      value: showFormData.value.warehouseName
    },
    {
			label: '处置时间:',
			value: showFormData.value.createTime
		},
		{
			label: '备注:',
			value: showFormData.value.usagePurpose
		}
	])

	// tableData
	const tableColumns = ref([{
			prop: 'code',
			label: '耗材编码'
		},
		{
			prop: 'name',
			label: '耗材名称'
		},
		{
			prop: 'specification',
			label: '规格'
		},
		{
			prop: 'unit',
			label: '单位'
		},
		{
			prop: 'categoryName',
			label: '耗材分类'
		},
		{
			prop: 'stock',
			label: '当前库存'
		},
		{
			prop: 'quantity',
			label: '处置数量'
		}
	])

	const tableData = ref([])

	// 点击编号时触发的方法
	const handleClickTag = (id) => {
		// 思路：点击编号时候，调用接口获取详情接口然后根据返回的数据组合成showFormData格式的数据
		getDisposalMaterialDetail(id).then(res => {
			if (res.code === 200) {
        let type=''
        if (res.data.type == 1) type='报废清理';
        if (res.data.type == 2) type='盘亏处理';
        if (res.data.type == 3) type='毁损处理';
        if (res.data.type == 4) type='丢失';
        if (res.data.type == 5) type='其他';
        let status=''
        if (res.data.status == 0) status='待处理';
        if (res.data.status == 1) status='已处置';
        if (res.data.status == 2) status='已取消';
				nextTick(() => {
					showFormData.value = res.data
          showFormData.value.status = status
          showFormData.value.type = type
					tableData.value = res.data.materialDisposalDetails
				})
			}
		})
		// 给Drawer传递数据 打开 Drawer
		drawerVisible.value = true
	}

	// 关闭 Drawer 的方法
	const closeDrawer = () => {
		drawerVisible.value = false
	}

	// 删除耗材分类
	const deleteConsumablesDisposalData = (row) => {
    ElMessageBox.confirm( '确定删除该处置信息吗?',  '系统警告',    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      deleteConsumablesDisposal(row.id).then(res => {
        if (res.code === 200) {
          ElMessage.success('删除成功')
          getDisposalListData()
        }
      }).catch(err => {
        ElMessage.error('删除失败')
      })
    }).catch(() => {
      console.log('取消删除')
    })

	}

	/*********** 页面加载时获取数据 *********/
	onMounted(() => {
		//获取仓库数据
		getWareHouseData()
		// 获取处置列表
		getDisposalListData()
	})
</script>

<template>
	<el-space>
		<!-- 搜索框 -->
		<el-form :inline="true" :model="queryForm">

			<el-form-item label="">
				<el-space>
					<el-select v-model="queryForm.warehouseId" placeholder="请选择处置仓库" style="width: 200px" clearable>
            <el-option v-for="wh in wareHouse" :label="wh.name" :value="wh.id" :key="wh.id" >

            </el-option>
            <!-- 使用图标组件 -->
            <template #prefix>
              <el-icon>
                <Search />
              </el-icon>
            </template>
					</el-select>
					<el-input v-model="queryForm.orderNo" placeholder="请输入处置单号" :icon="Search" clearable
						style="width: 230px" :prefix-icon="Search" />
          <el-button type="primary" :icon="Search" @click="handleDisposalSearch">
						搜索
					</el-button>
					<el-button type="primary" plain :icon="Refresh" @click="handleDisposalReset">
						重置
					</el-button>
					<el-button plain type="primary" :icon="Plus" @click="addDisposalData">
						新增
					</el-button>
				</el-space>
			</el-form-item>
		</el-form>
	</el-space>

	<!-- 新增耗材领用弹框表单 -->
		<el-dialog v-model="formVisible" @close="handleCancel" close-on-click-modal="false" :title="title" width="75%">
			<el-form :model="disposalForm" :rules="rules" ref="formRef" label-width="120px" inline>
				<el-form-item label="处置仓库" prop="warehouseId" :rules="[{required:true,message:'请选择处置仓库'}]">
					<el-select v-model="disposalForm.warehouseId" placeholder="请选择处置仓库" style="width: 200px" clearable>
						<el-option v-for="wh in wareHouse" :label="wh.name" :value="wh.id" :key="wh.id" />
					</el-select>
				</el-form-item>

				<!-- 处置类型下拉框，1-报废清理 2-盘亏处理 3-毁损清理 4-丢失 5-其他 -->
				<el-form-item label="处置类型" prop="type" style="width: 300px" clearable>
					<el-select v-model="disposalForm.type" placeholder="请选择处置类型">
						<el-option label="报废清理" value="1" />
						<el-option label="盘亏处理" value="2" />
						<el-option label="毁损清理" value="3" />
						<el-option label="丢失" value="4" />
						<el-option label="其他" value="5" />
					</el-select>
				</el-form-item>

				<el-form-item label="备注" prop="remark" class="full-width" style="margin-top: 10px">
					<el-input v-model="disposalForm.remark" type="textarea" :rows="3" placeholder="请输入备注内容"
						maxlength="200" show-word-limit />
				</el-form-item>

				<ConsumableList :wid="disposalForm.warehouseId" @consumableSelect="handleConsumablesSelect" />

				<div class="dialog-footer">
					<el-button @click="handleCancel">取消</el-button>
					<el-button type="primary" @click="handleSubmit">确定</el-button>
				</div>
			</el-form>
		</el-dialog>

		<!--借用信息列表-->
  <el-table :data="disposalList" table-layout="auto" height="80%" style="margin-top: 10px;">
    <el-table-column prop="orderNo" label="处置单号" align="left"/>
    <el-table-column prop="operator" label="处置人" align="center"/>
    <el-table-column prop="status" label="处置类型" align="center">
      <template #default="scope">
        <el-tag type="primary" v-if="scope.row.type===1">报废清理</el-tag>
        <el-tag type="warning" v-if="scope.row.type===2">盘亏处理</el-tag>
        <el-tag type="success" v-if="scope.row.type===3">毁损清理</el-tag>
        <el-tag type="info" v-if="scope.row.type===4">丢失</el-tag>
        <el-tag type="danger" v-if="scope.row.type===5">其他</el-tag>
      </template>
    </el-table-column>

    <el-table-column prop="warehouseName" label="处置仓库" align="center"/>
				<el-table-column prop="createTime" label="处置日期" align="center" />
				<!-- <el-table-column prop="remark" label="备注" align="center">
			<template #default="scope">
				<el-tooltip :content="scope.row.remark" placement="top"
					:disabled="!scope.row.remark || scope.row.remark.length <= 10">
					<span class="table-cell-truncate">{{ scope.row.remark }}</span>
				</el-tooltip>
			</template>
		</el-table-column> -->
				<el-table-column label="操作" align="center" width="180">
					<template #default="scope">
						<el-space>
              <el-link type="primary" :icon="View" @click="handleClickTag(scope.row.id)">
								查看
							</el-link>
							<el-link type="danger" link :icon="Delete"
								@click="deleteConsumablesDisposalData(scope.row)">
								删除
							</el-link>
						</el-space>
					</template>
				</el-table-column>
			</el-table>

			<!-借用详情抽屉->
				<Drawer v-model:visible="drawerVisible" :formData="showFormData" :title="'耗材处置详情'"
					:formDataValues="formDataValues" :tableColumns="tableColumns" :tableData="tableData"
					@close="closeDrawer" />
</template>

<style scoped lang='less'>
	.mb-4 {
		margin-bottom: 1rem;
	}

	.dialog-footer {
		display: flex;
		justify-content: flex-end;
		margin-top: 20px;
	}

	.el-form-item {
		margin: 0;
	}

	// 添加级联面板样式
	:deep(.cascader-popper) {
		.el-cascader-node:not(.is-leaf)>.el-cascader-node__label {
			color: #409EFF;

			&::after {
				content: '（可选）';
				font-size: 12px;
				color: #999;
			}
		}
	}

	.full-width {
		width: 100%;

		.el-textarea {
			width: 100%;
		}
	}

	.table-cell-truncate {
		display: inline-block;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		max-width: 200px;
		/* 根据实际情况调整 */
	}
</style>